<script setup lang="ts">
import type { Recordable } from '@vben/types';

import { ref, computed, watch, h, markRaw } from 'vue';

import {
  Page,
  useVbenDrawer,
  type VbenFormProps,
  confirm,
  prompt,
} from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';

import { Modal, Popconfirm, Space, Tabs, Input, message } from 'ant-design-vue';
const { TabPane } = Tabs;
import dayjs from 'dayjs';

import {   
  useVbenVxeGrid,
  vxeCheckboxChecked,
  type VxeGridProps 
} from '#/adapter/vxe-table';

import {
  refundTaxSettleExport,
  refundTaxSettleList,
  refundTaxSettleRemove,
  refundTaxSettleSubmit,
  refundTaxSettleApprove,
  refundTaxSettleInfo,
} from '#/api/trade/refundTaxSettle';
import type { RefundTaxSettleForm, RefundTaxSettleVO } from '#/api/trade/refundTaxSettle/model';
import { commonDownloadExcel } from '#/utils/file/download';

import refundTaxSettleDrawer from './refundTaxSettle-drawer.vue';
import { querySchema, getColumns } from './data';
import { APPROVE_STATUS } from '../constants';

// 状态标签页配置
const statusTabs = [
  { key: '', label: '全部' },
  { key: 'draft', label: '待提交', status: 'draft' },
  { key: 'waiting', label: '待审核', status: 'waiting' },
  { key: 'passed', label: '已通过', status: 'passed' },
  { key: 'rejected', label: '已驳回', status: 'rejected' },
  { key: 'invalid', label: '已作废', status: 'invalid' },
];

// 当前激活的状态标签
const activeTab = ref('');

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
  // 不需要直接删除
  // fieldMappingTime: [
  //  [
  //    'createTime',
  //    ['params[beginTime]', 'params[endTime]'],
  //    ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
  //  ],
  // ],
};

// 为每个状态创建独立的表格配置
const createGridOptions = (status: string): VxeGridProps => ({
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  // 根据状态动态生成列配置
  columns: getColumns(status),
  // height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const params = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        };
        // 只有当status不为空时才添加status参数
        if (status) {
          params.status = status;
        }
        return await refundTaxSettleList(params);
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到，每个状态tab使用不同的ID
  id: `trade-refundTaxSettle-${status}`,
});

// 为每个状态创建独立的表格实例
const tableInstances = ref<Record<string, any>>({});

// 初始化所有状态的表格实例
statusTabs.forEach((tab) => {
  const [BasicTable, tableApi] = useVbenVxeGrid({
    formOptions,
    gridOptions: createGridOptions(tab.key),
  });
  tableInstances.value[tab.key] = { BasicTable: markRaw(BasicTable), tableApi };
});

// 获取当前激活状态的表格实例
const currentTableInstance = computed(() => {
  return tableInstances.value[activeTab.value];
});

// 状态切换处理函数
function handleStatusChange(status: string) {
  activeTab.value = status;
  tableInstances.value[status].tableApi.query();
}

const [RefundTaxSettleDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: refundTaxSettleDrawer,
});

function handleAdd() {
  // 添加新费用时，自动设置当前tab页对应的状态
  // 如果是"全部"tab页，则不设置状态，让用户自己选择
  const data = activeTab.value ? { status: activeTab.value } : {};
  drawerApi.setData(data);
  drawerApi.open();
}

async function handleEdit(row: Required<RefundTaxSettleForm>) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

async function handleDelete(row: Required<RefundTaxSettleForm>) {
  await refundTaxSettleRemove(row.id);
  await currentTableInstance.value.tableApi.query();
}

function handleMultiDelete() {
  const { tableApi } = currentTableInstance.value;
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<RefundTaxSettleForm>) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await refundTaxSettleRemove(ids);
      await tableApi.query();
    },
  });
}

function handleDownloadExcel() {
  const { tableApi } = currentTableInstance.value;
  commonDownloadExcel(
    refundTaxSettleExport,
    '退税结算数据',
    tableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}

// 打印功能
async function handlePrint(row: Required<RefundTaxSettleVO>) {
  // TODO: 实现打印功能
  message.info('打印功能待实现');
}
</script>

<template>
  <Page :auto-content-height="true">
    <Tabs
      v-model:activeKey="activeTab"
      @change="handleStatusChange"
      class="mb-4"
    >
      <TabPane v-for="tab in statusTabs" :key="tab.key" :tab="tab.label">
        <component
          :is="tableInstances[tab.key].BasicTable"
          table-title="退税结算列表"
        >
          <template #toolbar-actions>
            <Space>
              <a-button
                v-access:code="['trade:refundTaxSettle:export']"
                @click="handleDownloadExcel"
              >
                {{ $t('pages.common.export') }}
              </a-button>
            </Space>
          </template>
          <template #no="{ row }">
            <a
              @click="handleEdit(row)"
              class="cursor-pointer text-blue-600 hover:text-blue-800"
            >
              {{ row.no }}
            </a>
          </template>
          <template #action="{ row }">
            <Space>
            </Space>
          </template>
        </component>
      </TabPane>
    </Tabs>
    <RefundTaxSettleDrawer @reload="currentTableInstance.tableApi.query()" />
  </Page>
</template>
